<template>
    <div>
        <SupInput
        :InpList='InpList'
        :BtnList='BtnList'
        @clickFn='addFindFn'
        ></SupInput>
        <Suptable
        :headerData='headerData'
        :tableData='tableData'
        :pagesizeList='pagesizeList'
        @handleSizeChange="SizeChangeFn"
        @handleCurrentChange='CurrentChangeFn'
        :total='total'
        :pagesize='pagesize'
        :isImg='true'
        :ImgName='ImgName'
        :isTag='true'
        :TagName='TagName'
        :imgProp='imgProp'
        >
            <template v-slot:imgSlot='{ row }'>
                <div class="imgBox">
                    <img :src="row.row.avatar" alt="">
                </div>
            </template>
            <template v-slot:tagSlot='{ row }'>
                <el-tag>{{row.row.roleIds}}</el-tag>
            </template>
            <template v-slot:opera='{ row }'>
                <el-button @click="editClick(row.row)" type="text" size="small">编辑</el-button>
                <el-button @click="delClick(row.row.id)" type="text" size="small">删除</el-button>
            </template>
        </Suptable>
        <div>
            <el-dialog :title="isEdit?'修改信息':'新增管理员'" :visible.sync="dialogFormVisible">
                <div>
                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                        <el-form-item label="管理员名称" prop="username">
                            <el-input v-model="ruleForm.username"></el-input>
                        </el-form-item>
                        <el-form-item v-if="!isEdit" label="管理员密码" prop="password">
                            <el-input v-model="ruleForm.password" show-password></el-input>
                        </el-form-item>
                        <el-form-item label="管理员头像" id='upload'>
                            <el-upload
                                class="avatar-uploader"
                                action="https://www.shequlianshang.com/test/admin/storage/create"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                                <img v-if="ruleForm.avatar" :src="ruleForm.avatar" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="管理员角色" prop="roleIds">
                            <el-select class="seleWid" v-model="ruleForm.roleIds" placeholder="请选择">
                                <el-option
                                v-for="item in RoleOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                                @change='rolesFn'
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="邮箱地址" prop='mail'>
                            <el-input v-model="ruleForm.mail"></el-input>
                        </el-form-item>
                        <el-form-item label="手机号码" prop='tel'>
                            <el-input v-model="ruleForm.tel"></el-input>
                        </el-form-item>
                    </el-form>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="resetForm('ruleForm')">取 消</el-button>
                    <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>
<script>
import {adminList,roleList,addAdmin,detAdmin,queryAdmin,editAdmin} from '@/api/adminMock';
import SupInput from '@/components/SupInput';
import Suptable from '@/components/Suptable';
export default {
    name:'administrator',
    data(){
        var validateMail = (rule, value, callback) => {
            if (value == '') {
                callback();
            } else {
                let res = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
                if (!res.test(value.trim()) || value.trim()=='') {
                    callback(new Error('请输入正确的邮箱'));
                }else{
                    callback();
                } 
            }
        };
        var validateTel = (rule, value, callback) => {
            if (value == '') {
                callback();
            } else {
                let res = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
                if (!res.test(value.trim()) || value.trim()=='') {
                    callback(new Error('请输入正确的手机号'));
                }else{
                    callback();
                } 
            }
        };
        return{
            InpList:[
                {
                    model:'',
                    text:'请输入管理员名称'
                }
            ],
            BtnList:[
                {
                    icon:'el-icon-search',
                    name:'查找'
                },
                {
                    icon:'el-icon-edit',
                    name:'添加'
                }
            ],
            headerData:[
                {
                    prop:"id",
                    label:"管理员id",
                    // width:"150",
                },
                {
                    prop:"username",
                    label:"管理员名称",
                    // width:"200",
                },
                {
                    prop:"mail",
                    label:"邮箱",
                    // width:"260",
                },
                {
                    prop:"tel",
                    label:"手机号",
                    // width:"200",
                },
            ],
            tableData:[],
            pagesizeList:[5,10],
            total:0,
            pagenum:1,
            pagesize:5,
            ImgName:'管理员头像',
            TagName:'管理员角色',
            imgProp:'avatar',
            dialogFormVisible:false,
            isEdit:false,
            ruleForm: {
                username: '',
                password:'',
                avatar:'',
                roleIds:'',
                mail:'',
                tel:'',
            },
            rules: {
                username: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                    { min: 2, max: 100, message: '长度在2个字以上', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 8, max: 16, message: '长度在 8 到 16 个字符', trigger: 'blur' }
                ],
                roleIds: [
                   { required: true, message: '请选择角色', trigger: 'change' }
                ],
                mail: [
                    { validator: validateMail, trigger: 'blur' }
                ],
                tel: [
                    { validator: validateTel, trigger: 'blur' }
                ]
            },
            RoleOptions:[],
            editId:'',
        }
    },
    components:{SupInput,Suptable},
    methods:{
        //获取角色
        obtainRole(){
            let _self = this;
            roleList().then(res=>{
                if(res.meta.status==200){
                    _self.RoleOptions = res.data.RoleList;
                }
            })
           
        },
        // 获取列表数据
        obtainList(){
            let _self = this;
            let data = {
                pagenum:_self.pagenum,
                pagesize:_self.pagesize
            }
            _self.tableData = [];
            adminList(data).then(res=>{
                if(res.meta.status==200){
                    _self.total = res.data.total;
                    for(let item of res.data.arr){
                        _self.tableData.push({
                            id:item.id,
                            username:item.username,
                            mail:item.mail,
                            tel:item.tel,
                            avatar:item.avatar,
                            roleIds:_self.RoleOptions.filter((items,index)=>items.value==item.roleIds)[0].label
                        })
                    }
                }
            })
        },
        //编辑按钮
        editClick(row){
            let _self =this;
            _self.isEdit = true;
            let {avatar,mail,roleIds,tel,username,id} = row;
            let rolesValue = '';
            _self.editId = id
            for(let item of _self.RoleOptions){
                if(item.label == roleIds){
                    rolesValue = item.value
                }
            }
            _self.dialogFormVisible = true;
            _self.ruleForm={
                username,
                password:'',
                avatar,
                roleIds:rolesValue,
                mail,
                tel,
            }
            _self.$nextTick(()=>{
                _self.$refs['ruleForm'].clearValidate()
            })
        },
        rolesFn(val){
            let _self =this;
            _self.ruleForm.roleIds = val;
        },
        //删除按钮
        delClick(id){
            let _self =this;
            let data = {id};
            detAdmin(data).then(res=>{
                if(res.meta.status == 200){
                    _self.obtainList()
                }
            })

        },
        //新增管理员 查询
        addFindFn(val){
            let _self = this;
            _self.$nextTick(()=>{
                _self.$refs['ruleForm'].clearValidate()
            })
            if(val==0){//查找
                let data = {
                    username:_self.InpList[0].model
                };
                queryAdmin(data).then(res=>{
                    // console.log(res);
                    if(res.meta.status==200){
                        _self.tableData = [];
                         for(let item of res.data.arr){
                            _self.tableData.push({
                                id:item.id,
                                username:item.username,
                                mail:item.mail,
                                tel:item.tel,
                                avatar:item.avatar,
                                roleIds:_self.RoleOptions.filter((items,index)=>items.value==item.roleIds)[0].label
                            })
                        }
                    }else{
                        _self.obtainList()
                    }
                })
            }else if(val==1){//添加
                _self.dialogFormVisible = true;
                _self.isEdit = false;
                _self.ruleForm={
                username: '',
                password:'',
                roleIds:'',
                avatar:'',
                mail:'',
                tel:'',
                }
            }
        },
        //图片上传成功时的钩子
        handleAvatarSuccess(res, file) {
            let _self = this;
            _self.ruleForm.avatar = URL.createObjectURL(file.raw);
        },
        //图片上传前的钩子
        beforeAvatarUpload(file) {
            let _self = this;
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
            _self.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isLt2M;
        },
        // 确定按钮
        submitForm(formName) {
            let _self = this;
            _self.$refs[formName].validate((valid) => {
            if (valid) {
                if(_self.isEdit){//修改
                    let data = _self.ruleForm;
                    data.id = _self.editId
                    editAdmin(data).then(res=>{
                        // console.log(res);
                        if(res.meta.status==200){
                            _self.obtainList();
                            _self.dialogFormVisible = false;
                            _self.$refs[formName].resetFields();
                        }
                    })
                }else{//新增
                    let {avatar,mail,roleIds,tel,username,password} = _self.ruleForm;
                    let data = {
                        avatar,
                        mail,
                        roleIds,
                        tel,
                        username,
                        password
                    }
                    addAdmin(data).then(res=>{
                        if(res.meta.status==200){
                            _self.obtainList();
                            _self.dialogFormVisible = false;
                            _self.$refs[formName].resetFields();
                        }
                    })
                }
            } else {
                console.log('error submit!!');
                return false;
            }
            });
        },
        //取消按钮
        resetForm(formName){
            let _self = this;
            _self.dialogFormVisible = false;
        },
        SizeChangeFn(val){
            let _self = this;
            _self.pagesize = val;
            _self.obtainList()
        },
        CurrentChangeFn(val){
            let _self = this;
            _self.pagenum = val;
            _self.obtainList()
        }
    },
    mounted(){
        let _self = this;
        _self.obtainRole()
        setTimeout(() => {
            _self.obtainList()   
        }, 200);
    },
}
</script>
<style>
.imgBox{
    width: 40%;
    height: 60px;
    margin: 0 auto;
}
.imgBox>img{
    width: 100%;
    height: 100%;
}
#upload{
    height: 178px;
}
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
.seleWid{
    width: 100%;
}
</style>